<#include "/includes/vars.inc"> 
<@pp.dropOutputFile />
<#assign fileName = "${javaDir}${packageDir}/service/support/UserDetailsServiceImpl.java">
<#if includeLoginSpring && !pp.outputFileExists(fileName)>
	<@pp.changeOutputFile name="${fileName}" />
	<#assign loginEntity = config.login.@entity[0]>
	
package ${project.@rootPackage}.service.support;

import java.util.ArrayList;
import java.util.Collection;
import ${project.@rootPackage}.domain.${loginEntity};
import ${project.@rootPackage}.service.${loginEntity}Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

/**
 * Authentication service class
 * <#if project.@author[0]??>@author ${project.@author}</#if>
 */
@Service("userDetailsService")
public class UserDetailsServiceImpl  implements UserDetailsService  {

    @Autowired
    ${loginEntity}Service ${loginEntity?uncap_first}Service;
        
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //org.springframework.security.core.userdetails.User user = users.get(username);
        ${loginEntity} user = ${loginEntity?uncap_first}Service.findByLogin(username);
        UserDetails userDetails;
        if (user != null) {
            boolean enabled = true;
            boolean accountNonExpired = true;
            boolean credentialsNonExpired = true;
            boolean accountNonLocked = true;
            Collection<GrantedAuthority> userAuthorities = new ArrayList<GrantedAuthority>();
            userAuthorities.add(new GrantedAuthorityImpl(user.getRol().toString()));

            userDetails = new org.springframework.security.core.userdetails.User(
                    user.getLogin(),
                    user.getPassword(),
                    enabled,
                    accountNonExpired,
                    credentialsNonExpired,
                    accountNonLocked,
                    userAuthorities);
            
            System.out.println("loadUserByUsername: " + userDetails.toString());
        } else {
            throw new UsernameNotFoundException("UserAccount for name \"" + username + "\" not found.");
        }

        return userDetails;
    }
     
}
</#if>